package com.example.demo.controller;

import com.example.demo.annotation.OnlyAdmin;
import com.example.demo.entity.SysUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class HomeController {

    private String returnUrl = "/";  //存储返回的url

    //模拟数据库，存放用户信息
    private static Map<String, SysUser> userdb = new HashMap<String, SysUser>();

    static {
        userdb.put("admin", new SysUser("admin", "admin"));
        userdb.put("guest", new SysUser("guest", "guest"));
    }

    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("/product")
    public String product() {
        return "product";
    }

    @RequestMapping("/user")
    @OnlyAdmin  //自定义注解
    public String user() {
        return "user";
    }


    @GetMapping("/login")
    public String login(@RequestParam(value = "returnUrl",required = true,defaultValue ="/" )String url) {
        returnUrl=url;
        return "login";
    }


    @PostMapping("/login")
    @ResponseBody
    public String login(HttpSession session, @RequestParam("name") String username, @RequestParam("pwd")String password) {

        session.setAttribute("status",false);

        SysUser user=(SysUser)userdb.get(username);
        if(user==null){
            return "0";
        }else {
           if(!user.getPassword().equals(password)){
               return "1";
           }else{
               session.setAttribute("status",true);
               session.setAttribute("loginUser",user);
               return returnUrl;
           }
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.setAttribute("status",false);
        session.removeAttribute("loginUser");
        return "redirect:/";
    }



}
